//
//  AddCompletePhotoViewController.m
//  eWindowBusiness_ios
//
//  Created by WYC on 2018/7/30.
//  Copyright © 2018年 EW. All rights reserved.
//

#import "TakeMultiPhotoViewController.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>

@interface TakeMultiPhotoViewController ()<UIAlertViewDelegate>
{
    NSMutableArray *imagePathArray;
    NSMutableArray *currentImagePathArray;
    NSInteger currentIndex;
    NSInteger currentYBIndex;
}
@property (weak, nonatomic) IBOutlet UIImageView *preImageView;
@property (weak, nonatomic) IBOutlet UILabel *preBtn;
@property (weak, nonatomic) IBOutlet UIImageView *nextImageView;
@property (weak, nonatomic) IBOutlet UILabel *detailLabel;
@property (weak, nonatomic) IBOutlet UIImageView *backImageView;
@property (weak, nonatomic) IBOutlet UIView *bottomView2;
@property (weak, nonatomic) IBOutlet UIView *bottomView1;
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray <UIImageView *>*imageCollection;
@property (weak, nonatomic) IBOutlet UILabel *nextBtn;
@property (weak, nonatomic) IBOutlet UIButton *prestepBtn;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray <UIButton *>*btnCollection;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
- (IBAction)deleteAction:(id)sender;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic)AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property(nonatomic)AVCaptureDeviceInput *input;

//当启动摄像头开始捕获输入
@property(nonatomic)AVCaptureMetadataOutput *output;

//照片输出流
@property (nonatomic)AVCaptureStillImageOutput *ImageOutPut;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property(nonatomic)AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;
- (IBAction)preAction:(id)sender;

@end

@implementation TakeMultiPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (!self.maxcount ) {
        self.maxcount = 1;
    }
   
    if (self.maxcount == 1) {
        self.nextBtn.text = @"完成";
        self.nextImageView.image = [UIImage imageNamed:@"图层 15 拷贝"];
    }
    self.preBtn.hidden = self.preImageView.hidden = self.prestepBtn.hidden = YES;
    currentYBIndex = 0;
    if ( [self checkCameraPermission]) {
        
        [self customCamera];
        for (UIImageView *tapImageView in _imageCollection) {
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
            tap.numberOfTapsRequired  = 1;
            tap.numberOfTouchesRequired = 1;
            [tapImageView addGestureRecognizer:tap];
        }
        imagePathArray = [NSMutableArray arrayWithCapacity:0];
        currentImagePathArray = [NSMutableArray arrayWithCapacity:0];
        self.backImageView.hidden = YES;
        self.deleteBtn.hidden = YES;
        [self.view addSubview:self.backImageView];
        [self.view addSubview:self.deleteBtn];
        [self.view addSubview:self.bottomView1];
        [self.view addSubview:self.bottomView2];
        
    }
    if (self.alreadyArray) {
        currentImagePathArray = self.alreadyArray;
        [imagePathArray addObject:self.alreadyArray];
        [self loadScrollView];
    }
    self.detailLabel.text = [NSString stringWithFormat:@"轻触拍摄（最多传%li张照片）",self.maxNum];

}
-(void)tap:(UITapGestureRecognizer *)tap
{
    UIView *view =tap.view;
    self.backImageView.hidden = NO;
    self.deleteBtn.hidden = NO;
    self.backImageView.image = [UIImage imageWithContentsOfFile:currentImagePathArray[view.tag-1]];
    currentIndex = view.tag - 1;
    self.detailLabel.text = @"点击继续拍照";
}
- (IBAction)deleteAction:(UIButton *)sender {
    NSInteger index = [self.btnCollection indexOfObject:sender];
    [currentImagePathArray removeObjectAtIndex:index];
    [self loadScrollView];
    if (self.backImageView.hidden == NO) {
        if (currentImagePathArray.count > currentIndex) {
            self.backImageView.image = [UIImage imageWithContentsOfFile:currentImagePathArray[currentIndex]];
        }else
        {
            currentIndex--;
            if (currentIndex<0) {
                self.backImageView.hidden = YES;
                self.deleteBtn.hidden = YES;
            }else
            {
                self.backImageView.image = [UIImage imageWithContentsOfFile:currentImagePathArray[currentIndex]];
            }
            
        }
        
    }
    
}

- (IBAction)cancelAction:(id)sender {
    [self disMiss];
}
- (IBAction)takePhoto:(id)sender {
    if (currentImagePathArray.count == self.maxNum) {
        [self.view makeToast:[NSString stringWithFormat:@"最多拍摄%li张",self.maxNum]];
        return;
    }
    if (self.backImageView.hidden) {
        [self shutterCamera];
    }else
    {
        self.backImageView.hidden = YES;
        self.deleteBtn.hidden = YES;
        self.detailLabel.text = [NSString stringWithFormat:@"轻触拍摄（最多传%li张照片）",self.maxNum];

    }
}

- (IBAction)preAction:(id)sender {
    self.nextBtn.text = @"下一步";
    self.nextImageView.image = [UIImage imageNamed:@"图层 15 拷贝"];

    if (imagePathArray.count == currentYBIndex) {
        [imagePathArray addObject:currentImagePathArray];
    }else
    {
        [imagePathArray replaceObjectAtIndex:currentYBIndex withObject:currentImagePathArray];
    }
    currentYBIndex--;
    currentImagePathArray = [imagePathArray objectAtIndex:currentYBIndex];
    [self loadScrollView];
    if (currentYBIndex == 0) {
        self.preBtn.hidden = self.preImageView.hidden = self.prestepBtn.hidden = YES;
    }
}
- (IBAction)nextAction:(id)sender {
    if (currentImagePathArray.count == 0) {
        [self.view makeToast:@"至少需要拍摄一张照片"];
        return;
    }
    
    self.backImageView.hidden = YES;
    self.deleteBtn.hidden = YES;
    self.preBtn.hidden = self.preImageView.hidden = self.prestepBtn.hidden = NO;
    if (imagePathArray.count == currentYBIndex) {
        [imagePathArray addObject:currentImagePathArray];
        currentImagePathArray = [NSMutableArray arrayWithCapacity:0];
    }else
    {
        [imagePathArray replaceObjectAtIndex:currentYBIndex withObject:currentImagePathArray];
        currentImagePathArray = imagePathArray[currentYBIndex+1];

    }
    if (currentYBIndex+1 == self.maxcount) {
        NSLog(@"输出所有image-imagePathArray");
        if (self.nextBlock) {
            for (NSString *string in [imagePathArray firstObject]) {
                NSLog(@"%@",string);
            }
            self.nextBlock([imagePathArray firstObject]);
        }
        [self dismissViewControllerAnimated:YES completion:NULL];
        return;
    }
    currentYBIndex++;
    if (currentYBIndex == self.maxcount-1) {
        self.nextBtn.text = @"完成";
        self.nextImageView.image = [UIImage imageNamed:@"compelted"];
    }
    [self loadScrollView];
    
}

- (void)customCamera
{
    //使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //使用设备初始化输入
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    //生成输出对象
    self.output = [[AVCaptureMetadataOutput alloc]init];
    
    self.ImageOutPut = [[AVCaptureStillImageOutput alloc]init];
    
    //生成会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc]init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        
        [self.session setSessionPreset:AVCaptureSessionPreset1280x720];
        
    }
    
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
        
    }
    
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
    
    //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    
    //开始启动
    [self.session startRunning];
    
    //修改设备的属性，先加锁
    if ([self.device lockForConfiguration:nil]) {
        
        //闪光灯自动
        if ([self.device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [self.device setFlashMode:AVCaptureFlashModeAuto];
        }
        
        //自动白平衡
        if ([self.device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [self.device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        
        //解锁
        [self.device unlockForConfiguration];
        
        
    }
    
}







- (void)changeCamera{
    //获取摄像头的数量
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    //摄像头小于等于1的时候直接返回
    if (cameraCount <= 1) return;
    
    AVCaptureDevice *newCamera = nil;
    AVCaptureDeviceInput *newInput = nil;
    //获取当前相机的方向(前还是后)
    AVCaptureDevicePosition position = [[self.input device] position];
    
    //为摄像头的转换加转场动画
    CATransition *animation = [CATransition animation];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.duration = 0.5;
    animation.type = @"oglFlip";
    
    if (position == AVCaptureDevicePositionFront) {
        //获取后置摄像头
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
        animation.subtype = kCATransitionFromLeft;
    }else{
        //获取前置摄像头
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
        animation.subtype = kCATransitionFromRight;
    }
    
    [self.previewLayer addAnimation:animation forKey:nil];
    //输入流
    newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
    
    
    if (newInput != nil) {
        
        [self.session beginConfiguration];
        //先移除原来的input
        [self.session removeInput:self.input];
        
        if ([self.session canAddInput:newInput]) {
            [self.session addInput:newInput];
            self.input = newInput;
            
        } else {
            //如果不能加现在的input，就加原来的input
            [self.session addInput:self.input];
        }
        
        [self.session commitConfiguration];
        
    }
    
    
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ) return device;
    return nil;
}


#pragma mark- 拍照
- (void)shutterCamera
{
    AVCaptureConnection * videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    if (videoConnection ==  nil) {
        return;
    }
    
    [self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        if (imageDataSampleBuffer == nil) {
            return;
        }
        
        NSData *imageData =  [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        [currentImagePathArray addObject:[self getPath:imageData]];
        [self loadScrollView];
        
    }];
    
}

-(void)loadScrollView
{
    for (UIImageView *imageView in _imageCollection) {
        imageView.hidden = YES;
    }
    for (UIButton *btn in _btnCollection) {
        btn.hidden = YES;
    }

    for (int i = 0; i < currentImagePathArray.count; i++) {
        self.imageCollection[i].image = [UIImage imageWithContentsOfFile:currentImagePathArray[i]];
        self.imageCollection[i].hidden = NO;
        self.btnCollection[i].hidden = NO;
        self.scrollView.contentSize = CGSizeMake(self.imageCollection[i].right, self.scrollView.height);
    }
}

-(NSString *)getPath:(NSData *)data
{
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
    [formatDate setDateFormat:@"yyyyMMddhhmmssSSS"];
    NSString *time = [formatDate stringFromDate:date];
    NSString *ImagePath = [NSString stringWithFormat:@"/%@%@.png",[DataManage getObjectForKey:@"phone"],time];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
    NSString *filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;

}
/**
 * 保存图片到相册
 */





- (void)disMiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark- 检测相机权限
- (BOOL)checkCameraPermission
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alertView.tag = 100;
        [alertView show];
        return NO;
    }
    else{
        return YES;
    }
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0 && alertView.tag == 100) {
        
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }
    
    if (buttonIndex == 1 && alertView.tag == 100) {
        
        [self disMiss];
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)deleteCurrentAction:(id)sender {
    [currentImagePathArray removeObjectAtIndex:currentIndex];
    [self loadScrollView];
    if (currentImagePathArray.count > currentIndex) {
        self.backImageView.image = [UIImage imageWithContentsOfFile:currentImagePathArray[currentIndex]];
    }else
    {
        currentIndex--;
        if (currentIndex<0) {
            self.backImageView.hidden = YES;
            self.deleteBtn.hidden = YES;
        }else
        {
            self.backImageView.image = [UIImage imageWithContentsOfFile:currentImagePathArray[currentIndex]];
        }
        
    }

}

@end
